<template>
  <div>
    <a-modal
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      width="1000px"
    >
      <div
        style="font-size: 25px;
        font-weight: bold;
        background-color:rgba(220,20,60,0.8);"
      >
        <img
          src="/src/assets/alarm/icon_huojing.png"
          style="margin: 1%;"
          alt="">
        火情信息
      </div>
      <div  class="modal-content">
        <div  style="padding-top: 15px;" class="fireVideo">
          <span style="font-weight: 700;margin-bottom: 20px;margin-top: 20px;">
            报警视频：
          </span>
          <video
            width="100%"
            height="100%"
            :src="apiData.fireVideo"
            controls
            autoplay
            muted
            @loadeddata="onVideoLoaded"
            @error="onVideoError"
            type="video/mp4"
          >
          </video>
        </div>
        <div class="info-container">
          <div class="info-item">
            <span>上报人</span>
            <a-input :value="apiData.fireInitiatorUser" ></a-input>
          </div>
          <div class="info-item">
            <span>预警名称</span>
            <a-input :value="apiData.fireName" ></a-input>
          </div>
          <div class="info-item">
            <span >上报人电话</span>
            <a-input :value="apiData.fireInitiatorUserPhone"></a-input>
          </div>
          <div class="info-item">
            <span>所属主体</span>
            <a-input :value="apiData.enterpriseName" ></a-input>
          </div>
          <div class="info-item">
            <span>所属建筑</span>
            <a-input :value="apiData.buildName"></a-input>
          </div>
          <div class="info-item">
            <span>详情地址</span>
            <a-input :value="apiData.location"></a-input>
          </div>
          <div class="info-item">
            <span>确定时间</span>
            <a-input :value="apiData.fireConfirmTime" ></a-input>
          </div>
          <!-- <div class="info-item">
            <span :value="apiData.fireExecutionStatus">火情状态</span>
            <a-input ></a-input>
          </div>
          <div class="info-item">
            <span>结束时间</span>
            <a-input :value="apiData.endTime" ></a-input>
          </div> -->
        </div>
      </div>
      <div class="button-container">
        <!-- <a-button @click="confirmFire">确认火情</a-button> -->
        <a-button type="primary" @click="handleFireLocation">火情位置</a-button>
        <a-button @click="handleCloseSound">关闭声音</a-button>
        <!-- <a-button type="success" @click="handleEnterDetails">进入火情详情</a-button> -->
      </div>
      <template #footer>
        <a-button @click="handleCancel">关闭</a-button>
        <a-button type="primary" @click="handleOk">确认火情</a-button>
      </template>
    </a-modal>
    <!-- 新增百度地图模态框 -->
    <a-modal
      :visible="mapVisible"
      title="火情位置地图"
      @ok="handleMapOk"
      @cancel="handleMapCancel"
      width="800px"
    >
      <!-- 传递经纬度数据给 BaiduMap 组件，并监听 addressReceived 事件 -->
      <BaiduMap
        :showButtons="false"
        :bound="[{ lng: apiData.longitude, lat: apiData.latitude }]"
        @addressReceived="handleAddressReceived"
      />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue';
import { useEmitter } from '/@/store/modules/user';
import { inFireInfoListData, inFireInfoForm } from '/@/api/management/inFireInfo';
import { Modal, Input, Button } from 'ant-design-vue';
import BaiduMap from '/@/components/BMap';
import { router } from '/@/router'; // 引入路由实例
import { InFireNotification } from '/@/api/management/inFireNotification';
import { userInfo } from '/@/api/sys/user';
import { inFireInfoConfirm } from '/@/api/management/inFireInfo';
import warning from '/@/assets/warning/warning.mp3';

// 初始化模态框的可见状态
const visible = ref(false);
// 用于存储火情图片的URL
const fireImageUrl = ref(''); 
// 用于存储WebSocket消息数据
const parsedMessage = ref(null); 
// 用于存储接口返回的数据
const apiData = ref<any>({ });
// 创建 Audio 对象
const audio = ref(new Audio(warning)); 
audio.value.loop = true;

// 标记是否已经进行过用户交互
let userInteracted = false;

// 处理音频播放错误
audio.value.onerror = () => {
  console.error(audio.value.error);
};

// 获取事件总线实例
const emitter = useEmitter();

// 处理模态框的确认事件
const handleOk = async () => {
    visible.value = false;
    audio.value.pause();
    audio.value.currentTime = 0;
    console.log('提交的数据:', parsedMessage.value);
    console.log('parsedMessageTid:', parsedMessage.value.id);
    try {
        const result = await userInfo();
        console.log('userInfo 接口请求结果:', result.user.userCode);

        // 调用 inFireInfoConfirm 接口并传入参数
        if (parsedMessage.value && parsedMessage.value.id) {
            const fireId = parsedMessage.value.id;
            const notifierCode = result.user.userCode;
            const response = await inFireInfoConfirm({ fireId, notifierCode });
            console.log('inFireInfoConfirm 接口请求成功:', response);
        }
    } catch (error) {
        if (error instanceof Error) {
            console.error('调用接口出错:', error.message);
        } else {
            console.error('调用接口出错:', error);
        }
    }
};

// 处理模态框的取消事件
const handleCancel = () => {
  visible.value = false;
  audio.value.pause(); 
  audio.value.currentTime = 0; 
};

// 新增百度地图模态框可见状态
const mapVisible = ref(false);

// 处理“火情位置”按钮点击事件
const handleFireLocation = () => {
  console.log('点击了火情位置按钮');
  mapVisible.value = true;
};

// 处理“关闭声音”按钮点击事件
const handleCloseSound = () => {
  audio.value.pause(); 
  audio.value.currentTime = 0; 
  console.log('点击了关闭声音按钮');
};

// 处理“进入火情详情”按钮点击事件
const handleEnterDetails = () => {
  console.log('点击了进入火情详情按钮');
  if (apiData.value.tid) {
    router.push({
      name: 'ViewsManagementInFireInfoList',
      query: {
        tid: apiData.value.tid,
        openDrawer: true // 新增参数，用于标记是否打开抽屉
      }
    });
  }
};

// 处理百度地图模态框的确认事件
const handleMapOk = () => {
  mapVisible.value = false;
};

// 处理百度地图模态框的取消事件
const handleMapCancel = () => {
  mapVisible.value = false;
};

// 封装调用接口的函数
const fetchData = async (tid) => {
  try {
    const response = await inFireInfoForm({ tid },tid);
    apiData.value = { ...apiData.value, ...response.inFireInfo }; 
    console.log('接口返回的数据:', apiData.value);
  } catch (error) {
    console.error('调用接口出错:', error);
  }
};

// 模拟用户交互，实际可以换成真实的用户操作事件
onMounted(() => {
  // 标记用户已交互
  userInteracted = true;
  emitter.on('fire-alarm-event', async (messageData) => {
    parsedMessage.value = messageData.content;
    visible.value = true;
    if (userInteracted) {
      audio.value.currentTime = 0; 
      await audio.value.play().catch((error) => {
        console.error('播放音频出错:', error);
      });
    }
    if (parsedMessage.value && parsedMessage.value.id) {
      console.log('获取到火情ID:', parsedMessage.value.id);
      fetchData(parsedMessage.value.id);
      // 添加跳转逻辑
      if (apiData.value.tid) {
        router.push({
          name: 'ViewsManagementInFireInfoList',
          query: {
            tid: apiData.value.tid,
            openDrawer: true // 新增参数，用于标记是否打开抽屉
          }
        });
      }
    }
  });
});

// 使用 watch 监听 apiData 的变化
watch(apiData, (newValue) => {
  if (newValue) {
    console.log('apiData 更新:', newValue);
  }
}, { deep: true });

// 视频加载完成事件处理函数
const onVideoLoaded = () => {
  console.log('视频加载完成');
};

// 视频加载出错事件处理函数
const onVideoError = (event) => {
  console.error('视频加载出错:', event.target.error);
};

// 处理子组件传来的地址信息
const handleAddressReceived = (address) => {
  apiData.value.location = address;
  console.log('接收到的地址:', address);
};
</script>

<style scoped lang="less">

.modal-content {
  display: flex;
  margin-top: 15px;
  // background-color: rgb(247, 144, 88);
}
// .fireVideo {
//   width: 300px;
//   height: 200px;
//   margin-right: 20px;
// }
.info-container {
  flex: 1;
  margin-left: 5%;
}
.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  margin-top: 10px;
  margin-right: 1%;
}
.info-item span {
  width: 90px; 
  margin-right: 10px;
}
.a-input {
  flex: 1;
}
.button-container {
  margin-top: 5%;
  width: 40%;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.fireVideo{
  width: 40%;
  height: 350px;
  margin-left: 2%;
}
</style>